package com.hyc.factory;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @projectName: SpringIOC
 * @package: com.hyc.factory
 * @className: beanfactory
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/3/24 16:30
 * @version: 1.0
 */
public class beanfactory {

    private static Properties properties;
    private static Map<String, Object> cache = new HashMap();

    static {
        properties = new Properties();
        try {
            properties.load(beanfactory.class.getClassLoader().getResourceAsStream("factory.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Object getDao(String beanName) {
        if (!cache.containsKey(beanName)) {
            synchronized (beanfactory.class) {
                if (!cache.containsKey(beanName)) {
                    //利用反射机制创建对象
                    //将对象放入我们的缓存里（map）
                    try {
                        String helloDao = properties.getProperty("helloDao");
                        Class clazz = Class.forName(helloDao);
                        Object object = clazz.getConstructor(null).newInstance();
                        cache.put(beanName, object);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return cache.get(beanName);
    }
}
